"""
/** Copyright 2020 Zhejiang Lab and Zhejiang University. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================
*/
"""
from django.db import models
from django.db import transaction
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
from django.core import validators
from django.utils import timezone

# Create your models here.
class ServerManager(BaseUserManager):
    use_in_migrations = True

    @transaction.atomic
    def _create_user(self, username, password, **kwargs):
        if not username:
            raise ValueError("The given username must be set")
        # if len(username) < 6:
        #     raise ValueError("The given username must be longer than 6")
        user = self.model(username=username, last_login=timezone.now(), **kwargs)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create(self, username, password, **kwargs):
        server = self._create_user(username, password, **kwargs)
        return server


class Server(AbstractBaseUser):
    username = models.CharField(max_length=20, unique=True, blank=False)

    objects = ServerManager()
    USERNAME_FIELD = 'username'

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True